<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script type="application/javascript" src="https://cdn.staticfile.org/vue/2.6.5/vue.min.js"></script>
<body>
<div id="app">
    <div class="box">
        <div v-show="isLogin">
            用户名:<input type="text" v-model="name" size="15"><button @click="login">登录</button>
        </div>
        <div v-for="line in lines">{{line.name}}:{{line.content}}</div>
    </div>
    <input type="text" v-model="message"><button @click="send">send</button>
</div>
<script>
    new Vue({
        el:'#app',
        data:function () {
            return {
                ws:{},
                message:'',
                lines:[],
                name:'',
                isLogin:true
            }
        },
        methods:{
            sendMsg(msg){
                this.ws.send(msg);
            },
            send(){
                let msg = {cmd:'chat',name:this.name,content:this.message};
                this.sendMsg(JSON.stringify(msg));
                // this.lines.push(msg);
                this.message = '';
            },
            login(){
                if(this.name == ''){
                    alert("请输入用户名");
                    return;
                }
                this.ws = new WebSocket("ws://localhost:8080/ws/chat");
                this.ws.onopen=(event) => {
                    console.log("连接成功");
                    let login = {cmd:'login',name:this.name};
                    this.ws.send(JSON.stringify(login));
                    this.isLogin = false;
                }
                this.ws.onclose=function(event){
                    console.log("连接关闭");
                }
                this.ws.onerror=function(event){
                    console.log("异常"+event);
                }
                this.ws.onmessage=(event) => {
                    console.log("收消息："+event.data);
                    let msg = JSON.parse(event.data);
                    if(msg.name === this.name){
                        msg.name= '我';
                    }
                    this.lines.push(msg);
                }
            }
        },
        mounted(){
        }
    })
</script>
</body>
</html>